package com.netpace.iem.umair.dal;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import com.netpace.iem.umair.model.Item;

public class ItemMemory implements IItemDao {
	private List<Item> items;
	Connection conn;

	// Default constructor is for Main memory Db
	public ItemMemory() {
		this.items = new ArrayList<Item>();
	}
	
	@Override
	public void insert(Item item){
		items.add(item);
	}
	
	@Override
	public void update(Item item, int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			items.remove(index);
			items.add(index, item);
		}
	}
	
	@Override
	public void delete(Item item, int pk) {
		int index = getIndex(item); 
		if ( index != -1 ) {
			items.remove(index);
		}
	}
	
	@Override
	public void delete(int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			items.remove(index);
		}
	}
	
	@Override
	public Item findById(int pk) {
		int index = getIndex(pk); 
		
		if ( index != -1 ) {
			return items.get(index);
		}
		
		return null;
	}
	
	@Override
	public List<Item> findAll(){
		return items;
	}
	
	private int getIndex(Item item) {
		if ( items.contains(item) ) 
			return items.indexOf(item);
		else
			return -1;
	}
	
	private int getIndex(int pk) {
		for (int i = 0; i < items.size(); i++) {
			if ( items.get(i).getId() == pk ) {
				return i;
			}
		}
		
		return -1;
	}
}
